﻿using IdentityModel.Client;
using JuCheap.Core.Infrastructure.Exceptions;
using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System.Threading.Tasks;

namespace JuCheap.Core.WebApi.Controllers
{
    /// <summary>
    /// 用户认证服务api
    /// </summary>
    [Route("api/[controller]")]
    public class AuthController : BaseApiController
    {
        private readonly IConfiguration _configuration;

        /// <summary>
        /// ctor
        /// </summary>
        public AuthController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 登陆接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("login")]
        [AllowAnonymous]
        public async Task<ActionResult<LoginResponseDto>> Login([FromBody]LoginRequestDto loginDto)
        {
            //向IdentityServer请求令牌
            using (var tokenClient = new HttpClient())
            {
                var response = await tokenClient.RequestPasswordTokenAsync(new PasswordTokenRequest
                {
                    Address = $"{_configuration.GetIdentityServerUrl()}connect/token",
                    ClientId = _configuration.GetApiId(),
                    ClientSecret = _configuration.GetApiSecret(),
                    Scope = _configuration.GetApiId(),
                    UserName = loginDto.LoginAccount,
                    Password = loginDto.Password
                });

                if (response.IsError)
                {
                    throw new BusinessException(response.Error);
                }

                var tokenInfo = new LoginResponseDto
                {
                    Token = response.AccessToken,
                    Expire = response.ExpiresIn
                };

                return Ok(tokenInfo);
            }
        }

        /// <summary>
        /// 登出接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("logout")]
        public async Task<ActionResult<bool>> Logout()
        {
            using (var tokenClient = new HttpClient())
            {
                var response = await tokenClient.RevokeTokenAsync(new TokenRevocationRequest()
                {
                    Address = $"{_configuration.GetIdentityServerUrl()}connect/revocation",
                    ClientId = _configuration.GetApiId(),
                    ClientSecret = _configuration.GetApiSecret(),
                    Token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "")
                });

                return Ok(true);
            }
        }
    }
}
